package daoJPA;

import java.util.List;

import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.persistence.EntityNotFoundException;
import javax.persistence.Query;
import javax.persistence.criteria.CriteriaQuery;

import dao.ICandidateCommentDAO;
import entityJPA.Candidatecomment;

public class JPACandidateCommentDAO implements ICandidateCommentDAO {
	private  EntityManagerFactory emf=null;
	public JPACandidateCommentDAO(EntityManagerFactory emf) {
		super();
		this.emf = emf;
	}

	public EntityManager getEntityManager(){
		return emf.createEntityManager();
	}
	
	@Override
	public void insert(Candidatecomment candidateComment) {
		EntityManager em=getEntityManager();
		try{
		
		em.getTransaction().begin();
		em.persist(candidateComment);
		em.getTransaction().commit();}
	catch(Exception ex){
		ex.printStackTrace();
	}
	em.close();
		
	}

	@Override
	public void update(Candidatecomment candidateComment) {
		EntityManager em = null;
        try {
			em = getEntityManager();
			em.getTransaction().begin();
			Candidatecomment c = null;
	        try {
	            c = em.find(Candidatecomment.class,candidateComment.getIdCandidateComment());
	    		c.setCandidateComment(candidateComment.getCandidateComment());
	        } catch (EntityNotFoundException ex){
	            ex.printStackTrace();
	        }  
	        em.merge(c);
			em.getTransaction().commit();
        } finally {
            if (em != null) {
                em.close();
            }
        }
		
		
	}

	@Override
	public void delete(Candidatecomment candidateComment) {
		EntityManager em = null;
        try {
			em = getEntityManager();
			em.getTransaction().begin();
			Candidatecomment c = null;
	        try {
	            c = em.getReference(Candidatecomment.class, candidateComment.getIdCandidateComment());
	        } catch (EntityNotFoundException ex){
	            ex.printStackTrace();
	        }
			em.remove(c);
			em.getTransaction().commit();
        } finally {
            if (em != null) {
                em.close();
            }
        }
		
	}

	@Override
	public Candidatecomment findById(int idCandidateComment) {
		try{
			EntityManager em=getEntityManager();
			em.getTransaction().begin();
			Candidatecomment c=em.find(Candidatecomment.class,idCandidateComment);
			em.getTransaction().commit();
			return c;
		}catch(Exception ex){
			ex.printStackTrace();
		}
		return null;
	}

	@Override
	public List<Candidatecomment> findAll() {
		EntityManager em = getEntityManager();
		Query q = null;
		try {
			CriteriaQuery cq = em.getCriteriaBuilder().createQuery();
			cq.select(cq.from(Candidatecomment.class));
			q = em.createQuery(cq);

		} catch (Exception e) {
			e.printStackTrace();
		}
		return q.getResultList();}

}
